package my.util;

public class RGBUtil {
	public static String intToRGB(Long number){
    	String binaryString = Long.toBinaryString(number);
    	String format = repairByte(binaryString, 32, "0");
    	
		String red2 = format.substring(8, 16);
		String green2 = format.substring(16, 24);
		String blue2 = format.substring(24, 32);
		
		Integer red = Integer.valueOf(red2, 2);
		Integer green = Integer.valueOf(green2, 2);
		Integer blue = Integer.valueOf(blue2, 2);
		
		String red16 = repairByte(Integer.toString(red, 16), 2, "0");
		String green16 = repairByte(Integer.toString(green, 16), 2, "0");
		String blue16 = repairByte(Integer.toString(blue, 16), 2, "0");
		
		StringBuilder str = new StringBuilder();
		str.append(red16).append(green16).append(blue16);
		String string = str.toString();
		String upperCase = string.toUpperCase();
    	return upperCase;
    }
    
    /**
     * 检测字符串长度，长度不足自动在前面补位
     * @param str 原始字符串
     * @param length 期望长度
     * @param repair 补位符
     * @return 格式化后的字符串
     */
    public static String repairByte(String str,int length,String repair){
    	StringBuilder str_=new StringBuilder();
		int index = length - str.length();
		for (int i = 0; i < index; i++) {
			str_.append(repair);
		}
		str_.append(str);
    	return str_.toString();
    }
    /**
     * 将
     * @param red
     * @param green
     * @param blue
     * @return
     */
    public static Integer rgbToInt(int red,int green,int blue){
    	int white = 0;
    	Integer rgbToInt = rgbToInt(white, red, green, blue);
    	return rgbToInt;
    }
    
    public static Integer rgbToInt(int white,int red,int green,int blue){
    	StringBuilder str = new StringBuilder();
    	str.append(intToBytes(white));
    	str.append(intToBytes(red));
    	str.append(intToBytes(green));
    	str.append(intToBytes(blue));
    	Integer valueOf = Integer.valueOf(str.toString(),2);
    	return valueOf;
    }
    
    public static Integer rgbToInt(String hex){
    	String red16 = hex.substring(0, 2);
    	String green16 = hex.substring(2, 4);
    	String blue16 = hex.substring(4, 6);
    	Integer red = Integer.valueOf(red16, 16);
    	Integer green = Integer.valueOf(green16, 16);
    	Integer blue = Integer.valueOf(blue16, 16);
    	Integer rgbToInt = rgbToInt(red, green, blue);
    	return rgbToInt;
    }
    
    public static String intToBytes(int number){
		String binaryString = Integer.toBinaryString(number);
		int binaryInt = Integer.parseInt(binaryString);
		String format = String.format("%08d",binaryInt);
		return format;
    }
}
